// fileName      :  test_middleware.go
// createdAt     :  2021-10-07
// description   :

package middlewares

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"zl-gin/constant"
	"zl-gin/services"
)

func Auth(c *gin.Context) {
	authHeader := c.Request.Header.Get("Authorization")

	if authHeader == "" {
		c.JSON(http.StatusOK, constant.ResponseEmptyToken)
		c.Abort()
		return
	}

	if authHeader[:6] != "Bearer" {
		c.JSON(http.StatusOK, constant.ResponseInvalidToken)
		c.Abort()
		return
	}

	token, tokenErr := services.ParseToken(authHeader[7:])
	if tokenErr != nil {
		zap.L().Debug("Token解析失败", zap.Error(tokenErr))
		c.Abort()
		c.JSON(http.StatusOK, constant.ResponseTokenExpire)
		return
	}

	userName := token.UserName
	userId := token.UserId
	c.Set("userName", userName)
	c.Set("userId", userId)
	c.Next()
}
